package com.example.boke.controller.admin;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.boke.entity.Type;
import com.example.boke.entity.User;
import com.example.boke.mapper.TypeMapper;
import com.example.boke.mapper.UserMapper;
import com.example.boke.service.UserService;
import com.example.boke.service.impl.UserServiceImpl;
import org.apache.catalina.Session;
import org.apache.catalina.mapper.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2021-05-01
 */
@Controller
@RequestMapping("/admin")
public class UserController {

    @Autowired
    private UserService userserviceimpl;

    @Autowired
    private UserMapper userMapper;


    @GetMapping({"login"})
    public String login()
    {
        return "admin/login";
    }

    @PostMapping(value = "/checkup")
    public String login(String nickname , String password, RedirectAttributes redirectAttributes, HttpServletRequest request)
    {

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();

        userQueryWrapper.eq("nickname",nickname);

        Integer result = userMapper.selectCount(userQueryWrapper);

        if (result == 0)
        {
            redirectAttributes.addFlashAttribute("message","账号不存在");
            return "redirect:/admin/login";
        }

        userQueryWrapper.clear();

        userQueryWrapper.eq("nickname",nickname).eq("password", password);
        User user = userMapper.selectOne(userQueryWrapper);
        System.out.println(user);
        if (user == null)
        {
            redirectAttributes.addFlashAttribute("message","密码错误");
            return "redirect:/admin/login";
        }

        HttpSession session = request.getSession();
        session.setAttribute("id",user.getId());
        session.setAttribute("nickname",user.getNickname());

        return "redirect:/admin/index";
    }

    @GetMapping(value = "/index")
    public String index()
    {
        return "admin/index";
    }

    @GetMapping(value = "/logout")
    public String logout(HttpServletRequest request)
    {


        HttpSession session = request.getSession();
        session.removeAttribute("id");
        session.removeAttribute("nickname");

        return "redirect:/amdin/login";

    }


}

